package com.example.androidproject.fps;

import android.util.Log;
import android.view.Choreographer;

public class FpsMonitor {
    private long lastFrameTimeNanos = 0;
    private Choreographer choreographer;
    private Choreographer.FrameCallback frameCallback;

    public void initFpsMonitor() {
        choreographer = Choreographer.getInstance();
        frameCallback = new Choreographer.FrameCallback() {
            @Override
            public void doFrame(long frameTimeNanos) {
                if (lastFrameTimeNanos == 0) {
                    lastFrameTimeNanos = frameTimeNanos;
                    choreographer.postFrameCallback(this);
                    return;
                }
                long diff = frameTimeNanos - lastFrameTimeNanos;
                // Convert to fps
                double fps = 1 / diff;
                Log.i("TAG", "doFrame: 当前帧率:"+fps);
                // Log or update UI with the new FPS value
                // 更新UI或者打印FPS值
                lastFrameTimeNanos = frameTimeNanos;
                choreographer.postFrameCallback(this);
            }
        };
    }

    public void start() {
        lastFrameTimeNanos = 0;
        choreographer.postFrameCallback(frameCallback);
    }

    public void stop() {
        choreographer.removeFrameCallback(frameCallback);
    }
}
